package com.LeetCode.StackAndHeap;


import org.junit.Test;

import java.util.PriorityQueue;

/**
 * 合并 k 个有序链表
 */
public class MegreKList {


    public ListNode mergeKLists(ListNode[] lists) {
        if(lists == null || lists.length == 0) return null;
        PriorityQueue<ListNode> heap = new PriorityQueue<>(lists.length,(a,b) -> a.val - b.val);

        ListNode dummy = new ListNode(0);
        ListNode p = dummy;

        for(ListNode node : lists){
            if(node!=null) heap.offer(node);
        }

        while(!heap.isEmpty()){
            p.next = heap.poll();
            p = p.next;
            if(p.next!=null)heap.offer(p.next);
        }

        return dummy.next;
    }

    @Test
    public void test(){
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        node1.next = node2;
        node2.next = node3;

        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(6);
        node4.next = node5;
        node5.next = node6;

        ListNode node7 = new ListNode(7);
        ListNode node8 = new ListNode(8);
        ListNode node9 = new ListNode(9);
        node7.next = node8;
        node8.next = node9;

        ListNode.printList(mergeKLists(new ListNode[]{node1,node4,node7}));

    }
}
